package com.faiz.example;

import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Palindrome {
    private final static int count = 1;

    @Test
    public void test() {
        String s = "babad";
        System.out.println(solution2(s));
        
    }

    // 方法2 solution2
    public String solution2(String s) {
        Map<Character, List<Integer>> map = new HashMap<>();
        int res = 1;
        int begin = 0;
        for (int j = 0; j < s.length(); j++) {
            if (map.containsKey(s.charAt(j))) {
                List<Integer> list = map.get(s.charAt(j));
                for (int i : list) {
                    if (isPalindrome(s, i, j)) {
                        if (j - i + 1 > res) {
                            res = j - i + 1;
                            begin = i;
                        }
                        break;
                    }
                }
                list.add(j);
            } else {
                List<Integer> list = new ArrayList<>();
                list.add(j);
                map.put(s.charAt(j), list);
            }
        }
        return s.substring(begin, begin + res);
    }

    public boolean isPalindrome(String s, int start, int end) {
        String tmp = s.substring(start, end + 1);
        return (new StringBuilder(tmp).reverse().toString().equals(s));
    }
}
